#include "client.hpp"

client::client()
{
    this->n = 0;
    int i = 0;
    for(; i < NB_BUFFER; i++)
    {
        this->rgb_data[i] = new unsigned char[WIDTH * HEIGHT * 3];
    }
}

client::~client()
{
    int i = 0;
    for(; i < NB_BUFFER; i++)
    {
        delete[] this->rgb_data[i];
        this->rgb_data[i] = nullptr;
    }
    
    close(this->sockfd);
}

void client::Init(const char *argv[])
{
    struct sockaddr_in serveraddr;
    socklen_t addrlen = sizeof(struct sockaddr_in);
    memset(&serveraddr, 0, addrlen);

    serveraddr.sin_family = AF_INET;
    serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
    serveraddr.sin_port = htons(atoi(argv[2]));

    this->sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(this->sockfd == -1)
    {
        fprintf(stderr,"socket error");
        exit(-1);
    }

    if(sendto(this->sockfd, "l", sizeof("l"), 0, (struct sockaddr*)&serveraddr, addrlen) == -1)
    {
        fprintf(stderr,"sendto error\n");
        exit(-1);
    }
}

void client::recv_rgb_data()
{
    if(this->n == 3)
    {
        this->n = 0;
    }
#if 1
    int data_size = WIDTH * HEIGHT * 3;  // 24位RGB数据
    int packet_size = 1024;  // 单个数据包的大小
    int total_packets = (data_size + packet_size - 1) / packet_size;

    for (int i = 0; i < total_packets; i++) {
        int offset = i * packet_size;
        int bytes_to_send = std::min(packet_size, data_size - offset);

        if(recvfrom(this->sockfd, this->rgb_data[this->n] + offset, bytes_to_send, 0, NULL, NULL) == -1)
        {
            fprintf(stderr,"recvfrom error");
            exit(-1);
        }
    }
#else
    int data_size = WIDTH * HEIGHT * 3;  // 24位RGB数据
    int packet_size = 1024;  // 单个数据包的大小
    int received_bytes = 0;

    while (received_bytes < data_size) {
        int bytes_to_recv = data_size - received_bytes;

        if(bytes_to_recv > packet_size){
            bytes_to_recv = packet_size;
        }        

        int bytes = recvfrom(this->sockfd, this->rgb_data[this->n] + received_bytes, bytes_to_recv, 0, NULL, NULL);
        if (bytes <= 0) {
            perror("接收数据失败");
            break;
        }
        received_bytes += bytes;
    }

    // if (received_bytes == data_size) {
    //     Print_GREEN("数据接收完成\n");
    // } else {
    //     Print_RED("数据接收未完成，接收的字节数: %d\n", received_bytes);
    // }
#endif

    switch (this->n)
    {
        case 0:
            rgb_to_image("output0.jpg");  
            break;
        case 1:
            rgb_to_image("output1.jpg");
            break;
        case 2:
            rgb_to_image("output2.jpg");
            break;
    }

    // printf("this->n = %d\n", this->n);
    this->n++;
}

void client::rgb_to_image(const char* filename)
{
    // 将 RGB 数据转换为 cv::Mat 对象
    cv::Mat image(HEIGHT, WIDTH, CV_8UC3, this->rgb_data[this->n]);

    // 将图像保存为文件
    cv::imwrite(filename, image);
}